home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1990: Night of the Living Disc / Night of the Living Disc.2mg / Dev.CD.5 / develop / develop.4 / WritingDevDrvr < prev   
Encoding:
Text File  |  1990-08-24  |  45.6 KB  |  686 lines  |  [04] ASCII Text (0x0000)

  1. Most developers write device drivers in assembly language, rarely considering a higher level, object-based language such as C++ for such a job. This article describes some of the advantages of higher level languages over assembly and warns of some of the gotchas you may encounter if you write a driver in C++. An example of a device driver written in C++ follows a brief discussion of drivers in general.
  2.  
  3. When you think of writing a device driver, your first reaction may be, "But I haven't brushed up on assembly language in some time." After taking a deep breath, you think of another approach: "Why can't I use a high-level language?" You can. One such language is C++. 
  4.  
  5. In comparison with standard C, C++ offers some definite advantages, including ease of maintenance, portability, and reusability. You can encapsulate data and functions into classes, giving future coders an easier job of maintaining and enhancing what you've done. And you can take advantage of most (but not all) of the powerful features of C++ when you write stand-alone code.
  6.  
  7. You will run into a few gotchas, including the fact that polymorphism is available only if you do some extra work (for a definition of polymorphism, see develop, Issue 2, page 180). Because the virtual tables (vTables) reside in the jump-table segment, a stand-alone code resource can't get at the vTables directly (more on this topic later). You also have to deal with factors such as how parameters are passed to methods, how methods are called, how you return to the Device Manager, how you compile and link the DRVR resource, and how the DRVR resource is installed when the machine starts up. We'll tackle some of these obstacles as we work through the sample device driver presented later in this article.
  8.  
  9.  
  10. WHY C++?
  11.  
  12. When someone suggests writing a device driver in anything other than assembly language, the common reaction is, "But you're talking to a device! Why would you want to use C++?" 
  13.  
  14. For communication with devices, assembly language admittedly gets the job done in minimal time, with maximum efficiency. But if you're writing something where code maintenance, portability, and high-level language functionality are just as important as speed and efficiency, a higher level language is preferable. 
  15.  
  16. Not all device drivers actually communicate with physical devices. Many device drivers have more esoteric functions, such as interapplication communication, as in the sample driver in this article. (In fact, DAs are of resource type DRVR and behave exactly the same way device drivers behave. DAs are even created the same way.) For these kinds of device drivers, C++ is a great language to use because you can take advantage of all the features of a high-level language, plus most of the object-based features of C++. Finally, device drivers have some nice features that make them appealing for general usage: 
  17.  
  18. •    They can remain in the system heap, providing a common interface for any application to easily call and use.
  19. •    They get periodic time (if other applications are not hogging the CPU).
  20.  
  21. Good examples of nondevice drivers are the .MPP (AppleTalk(r)) driver and the .IPC (A/ROSE(tm) interprocess communication) driver. Both these drivers provide pretty high-level functionality, but neither directly manipulates a device as such (except for the very low-level AppleTalk manipulations of communication ports). Of course, if you were writing code to communicate quickly and efficiently to a modem, for example, assembly language might be the better choice, depending on your need for efficiency and timing. For the purposes of this article, any reference to a device driver includes both types of drivers.
  22.  
  23. Clearly, higher level languages have a place, but what about object-based languages? Object-based languages provide a great framework for encapsulation of data and functions and hence increase the ease of maintenance and portability (if used elegantly). One question still remains: Why C++? 
  24.  
  25. Notables such as Bjarne Stroustrup and Stanley Lippman have pointed out some of the advantages C++ offers over conventional high-level languages. C++ offers great extensions, such as operator and function overloading, to standard C. C++ is much more strongly type checked than C, so it saves us programmers from ourselves. 
  26. C++ classes offer a way to encapsulate data - and functions that operate on the data - within one unit. You can make different elements and functions "private" to objects of only one class or "public" to objects of every type. The private and public nature of data and member functions allows you to accomplish real encapsulation.
  27.  
  28.  
  29. SOME LIMITATIONS
  30. As noted, one valuable feature of C++, polymorphism, is not readily available when you write a device driver in C++. Other limitations involve working with assembly language, possible speed sacrifices, work-arounds for intersegment calls, and mangled procedure names. 
  31.  
  32. Polymorphism 
  33. Because a device driver is a stand-alone code resource, there is no "global" space or jump table. C++'s virtual function tables (vTables), which are the means to the polymorphism end, live in an application's global space. The loss of virtual tables is a limitation of stand-alone code, not a limitation of C++. Patrick Beard's article, "Polymorphic Code Resources in C++" (this issue), shows one way to work around this limitation. The work-around takes some extra work and is dependent on the current implementation of CFront, which may make future compatibility a problem. In the interests of clarity and compatibility, I have chosen not to use polymorphism for the example in this article.
  34.  
  35. Assembly-Language Muck
  36. Another difficulty is that we have to get our hands assembly-language dirty. The Device Manager is going to call the device driver with a few registers pointing to certain structures, and we'll have to put those on the stack so the C++ routines can get to them. Specifically, A0 points to the parameter block that is being passed, and
  37.  
  38. A1 has a handle to the Device Control Entry for the driver. Having to do some assembler work is a limitation of the operating system; the toolbox doesn't push the parameters onto the stack (now if there were glue to do that - ).
  39.  
  40. These registers must somehow make their way onto the stack as parameters to our routines because procedures take their parameters off the stack. When we've finished, we also have to deal with jumping to jIODone or plain RTSing, depending on the circumstances. For the simple driver shown in the example, we will in reality almost always jump via jIODone when finished with our routines. But, for drivers that wish to allow more than one operation at a time, the Prime, Control, and Status calls must return via an RTS to signal the Device Manager that the request has not been completed. The driver's routines should jump to jIODone only when the request is complete. 
  41.  
  42. We must also decide whether or not to call a C++ method directly from the assembly language "glue." If we call the method directly, we have to put the "this" pointer on the stack because it's passed implicitly to all object methods. We also have to use the "mangled" name generated by the compiler and used by the linker. (If you haven't had the opportunity to see mangled names, you'll find they're a joy to figure out without the help of our friend Mr. Unmangle.) So, if we choose to call extern C functions, as the example does, we run into yet another level of "indirection" before we get to the real meat of the matter.
  43.  
  44. Speed
  45. Some might say we sacrifice speed as well as efficiency - and they're correct. In general, compilers can't generate optimally speed-efficient code. They can come close, but nothing even approaches how the human mind tackles some tricky machine-level issues. Thus, we're at the mercy of the compiler - the loss of speed is the result of the compiler's inefficiency. 
  46.  
  47. You'll probably find the sample driver presented in this article pretty inefficient. But the trade-off is acceptable because speed isn't important in this case, and you can use all the features of an object-based language. In fact, in most instances you can limit assembly language to a few routines, which must be tightly coded, and use C++ for the rest.
  48.  
  49. Mangled Identifiers 
  50. If you're familiar with C++, you've undoubtedly seen the visions of unreadability created by CFront. But, if you're still unfamiliar with C++ in practice, here's an explanation. CFront is simply a preprocessor that creates C code, which is passed to the C compiler. So CFront has to somehow take a function of the form
  51.  
  52. TDriver::iacOpen(ParmBlkPtr aParmBlkPtr) 
  53.  
  54. and create a C function name the C compiler can understand. The problem is that when the linker complains, it will use the mangled name, which is hard to decipher.
  55.  
  56. Here's how it looks:
  57.  
  58. from MPW Shell document    
  59. unmangle iacOpen__7TDriverFP13ParamBlockRec
  60. Unmangled symbol: TDriver::iacOpen(ParamBlockRec*)
  61.  
  62. It's clear why these names are referred to as mangled and unmangled. Fortunately, the unmangle tool provided with MPW allows you to derive the unmangled name from the mangled.
  63.  
  64. A SAMPLE C++ DRIVER
  65. The sample driver that follows illustrates some of the issues involved in writing a device driver in general, and specifically in C++. The code is in the folder labeled C++ Driver on the Developer Essentials disc. 
  66.  
  67. Communication
  68. The sample driver performs one basic function - interapplication communication (IAC) - under System 6. Under System 7 the services of this sample driver aren't necessary because IAC is built into the system. But the concepts presented here are still sound, and the driver works as well under System 7 as it does under System 6. The driver is installed at Init time with code that walks through the unit table looking for a slot. 
  69.  
  70. Class Structure
  71. The classes are fairly straightforward, serving as an example of how to use C++ to encapsulate data with methods without getting into some gnarly class hierarchies that would only obfuscate the point (and that aren't yet possible with stand-alone code). Two classes suffice: TDriver and TMessage. TDriver handles all the driving; it responds to each control and status call defined and handles opening and closing the driver. It keeps two simple data structures - an array of application names that have registered and an array of TMessage pointers that need to be received. TMessage handles the messages - who they're from, who they're addressed to, and what the message is. I think you'll find the declarations easy reading.
  72.  
  73. from TDriver.h
  74. class TDriver: public HandleObject {
  75. public:
  76.         // Constructor and destructor.
  77.         TDriver();
  78.         ~TDriver();
  79.     /* Generic driver routines. These are the only public interfaces we 
  80.      * show to the world.                                */
  81.     OSErr    iacOpen(ParmBlkPtr oParmBlock);
  82.     OSErr    iacPrime(ParmBlkPtr pParmBlock);
  83.     OSErr    iacControl(ParmBlkPtr cntlParmBlock);
  84.     OSErr    iacStatus(ParmBlkPtr sParmBlock);
  85.     OSErr    iacClose(ParmBlkPtr cParmBlock);
  86.     
  87. private:
  88.     // Control Routines.
  89.     /* RegisterApp takes the string in iacRecord.appName and finds a slot
  90.      * in the array for the name (hence it "registers" the application).
  91.      * SendMessage sends a message from one application to another (as
  92.      * specified by the iacRecord fields).
  93.      * ReceiveMessage puts the message string into the iacRecord.msgString
  94.      * field if there's a message for the requesting application.
  95.      * UnregisterApp removes the application's name from the array (hence 
  96.      * the application is "unregistered").                */
  97.     short        RegisterApp(IACRecord    *anIACPtr);
  98.     short        SendMessage(IACRecord    *anIACPtr);
  99.     short        ReceiveMessage(IACRecord    *anIACPtr);
  100.     short        UnregisterApp(IACRecord    *anIACPtr);
  101.     
  102.     // Status Routines
  103.     /* WhosThere returns the signature of other applications that 
  104.      * have registered.
  105.      * AnyMessagesForMe returns the number of messages waiting for the
  106.      * requesting application in iacRecord.actualCount.        */
  107.     void        WhosThere(IACRecord    *anIACPtr);
  108.     Boolean    AnyMessagesForMe(IACRecord    *anIACPtr);
  109.     
  110.     // Message array handling routines.
  111.     /* GetMessage gets the TMessPtr in fMessageArray[signature].
  112.      * SetMessage sets the pointer in fMessageArray[signature] to 
  113.      * aMsgPtr.                                 */
  114.     TMessPtr    GetMessage(short signature);
  115.     void        SetMessage(short index, TMessPtr    aMsgPtr);
  116.     
  117.     // AppName array handling routines.
  118.     /* GetAppName gets the application name in fAppNameArray[signature].
  119.      * SetAppName sets the application in fAppNameArray[signature] 
  120.      * to anAppName.                                */
  121.     char        *GetAppName(short signature);
  122.     void        SetAppName(short signature, char *anAppName);
  123.     
  124.     /* We keep an array of applications that can register with the 
  125.      * driver. I've arbitrarily set this at 16. We also keep an array 
  126.      * of TMessage pointers to be passed around. This is also arbitrarily 
  127.      * set at 16. In the future, I'd probably implement this as a list of
  128.      * messages.                                */
  129.     char        fAppNameArray[kMaxApps] [255];
  130.     TMessPtr    fMessageArray[kMaxMessages];
  131. };
  132.  
  133. from TMessage.h
  134. class TMessage {
  135. public:
  136.         /* Constructor and destructor. Constructor will build the message
  137.          * with the appropriate data members passed in.     */
  138.         TMessage(char *message, short senderSig, short receiverSig);
  139.         ~TMessage();
  140.                 
  141.         /* Two Boolean functions that simply query the message to see 
  142.          * if the message is destined for the signature of the 
  143.          * Requestor. Nice example of function overloading - in the 
  144.          * one case I just wanted to return true or false; in the other
  145.          * case I wanted to return who the message was from and the actual
  146.          * message string. This is also nice because we have only one 
  147.          * public member function returning any private information. */
  148.     Boolean    IsMessageForMe(short sigOfRequestor);
  149.     Boolean    IsMessageForMe(short sigOfRequestor, short *senderSig, 
  150.                      char *messageString);
  151.     
  152. private:
  153.     /* GetSenderSig returns fSenderSig.
  154.      * SetSenderSig sets fSenderSig to signature.            */
  155.     short        GetSenderSig();
  156.     void        SetSenderSig(short signature);
  157.     
  158.     /* GetReceiverSig returns fReceiverSig.
  159.      * SetReceiverSig sets fReceiverSig to signature.        */
  160.     short        GetReceiverSig();
  161.     void        SetReceiverSig(short signature);
  162.     
  163.     /* GetMessageString returns fMessageString.
  164.      * SetMessageString sets fMessageString to msgString.        */
  165.     char        *GetMessageString();
  166.     void        SetMessageString(char *msgString);
  167.     
  168.  
  169.     // Private data members. Again, we keep storage for the string here.
  170.     short        fSenderSig;
  171.     short        fReceiverSig;
  172.     char        fMessageString[255];
  173. };
  174.  
  175. The only remaining structure worthy of note is the IACRecord structure. 
  176. This structure is passed in the csParam field of the parameter block pointers passed to the driver. Essentially the IACRecord structure contains all the control information, or returns all the status information, the application needs to communicate - the signatures of the sender and receiver, the message and application name strings, and a couple of other control fields.
  177.  
  178. from IACHeaders.h
  179. struct IACRecord    {
  180.     // Signature number of application sending/receiving.
  181.     short    mySignature;
  182.  
  183.     // Signature of app that's either sent a message or          
  184.     // of app to which the current app is sending.
  185.     short    partnerSig;
  186.                     
  187.     // Index to cycle through the apps that have registered.
  188.     short    indexForWhosThere;
  189.  
  190.     // Nonzero if messages there for recipient.
  191.     short    actualCount;
  192.  
  193.     // Message string being sent or received.
  194.     char*    messageString;
  195.  
  196.     // String to register as.
  197.     char    *appName;
  198. };
  199.  
  200. Registering With the Driver
  201. To use the driver, an application registers itself with the driver, thus signifying that the application is able to receive and send messages. The driver returns a unique signature for the application to use throughout the communication session. A second (or third, or fourth) application also registers and communicates with other applications by sending and receiving messages using the correct signature. When an application is finished, it simply unregisters itself. Here are four of the methods that do most of the work:
  202.  
  203. from TDriver.cp
  204. /*********************************Comment****************************************
  205. * TDriver::RegisterApp looks to see if there's an open "slot".  If so, it sets 
  206. * the new AppName for that "slot" and returns the "slot" as the signature.  If it 
  207. * couldn't find any open "slots" then it returns the kNoMore error.
  208.  *********************************End Comment***********************************/
  209. short
  210. TDriver::RegisterApp(IACRecord *anIACPtr)
  211. {
  212. short        i = 0;
  213. short        canDo = kNoMore;
  214.  
  215. while ((i < kMaxApps) && (canDo == kNoMore))
  216.     {
  217.     if((this->GetAppName(i))[0] == kZeroChar)
  218.         {
  219.         canDo = kNoErr;
  220.         anIACPtr->mySignature = i;
  221.         this->SetAppName(i,anIACPtr->appName);
  222.         }
  223.     i++;
  224.     }
  225. return (canDo);
  226. } //  TDriver::RegisterApp
  227.  
  228. /*********************************Comment****************************************
  229. * TDriver::SendMessage has to instantiate a new message object.  It also has to
  230. * remember that message for later when someone tries to receive it.  To remember 
  231. * it, the TDriver object places it in the message pointer array.  If it couldn't 
  232. * find an open "slot" in the array, it returns the error kMsgMemErr, meaning it 
  233. * has no memory to store the pointer to the message and hence the message didn't 
  234. * get sent. Since the TDriver object is creating a new TMessage, it will destroy 
  235. * the TMessage when the time comes.
  236.  *********************************End Comment***********************************/
  237. short
  238. TDriver::SendMessage(IACRecord *anIACPtr)
  239. {
  240. TMessPtr    aMsgPtr;
  241. short        canDo = kNoMore;
  242. short        i = 0;
  243.  
  244. aMsgPtr = new TMessage(anIACPtr->messageString, anIACPtr->mySignature,
  245.         anIACPtr->partnerSig);
  246.  
  247.  
  248. if(aMsgPtr)
  249.     {
  250.     while ((i < kMaxMessages) && (canDo == kNoMore))
  251.         {
  252.         if(this->GetMessage(i) == nil)
  253.             {
  254.             this->SetMessage(i, aMsgPtr);
  255.             canDo = kNoErr;
  256.             }
  257.         i++;
  258.         }
  259.     if (canDo == kNoMore)
  260.         delete aMsgPtr;
  261.     } // if aMsgPtr
  262. else
  263.     canDo = kMsgMemErr;
  264. return (canDo);        
  265. } //  TDriver::SendMessage
  266.  
  267. /**********************************Comment***********************************
  268. * TDriver::ReceiveMessage finds any messages for the application whose 
  269. * signature is mySignature. It first checks to see if there are any 
  270. * messages. If so, it gets the message and asks the TMessage object to 
  271. * return the message string. Then it copies the message string to the 
  272. * calling application's message buffer, puts the sender's signature in 
  273. * "partnerSig", and puts the sender's application name in appName.
  274. * It then sets the "slot" in the message array to nil and disposes of the 
  275. * TMessage object. If there were messages, it returns the kYesMessagesForMe 
  276. * value; otherwise it returns kNoMore.
  277.  **********************************End Comment******************************/
  278. short
  279. TDriver::ReceiveMessage(IACRecord *anIACPtr)
  280. {
  281. TMessPtr        aMsgPtr;
  282. short            sender;
  283. char            *bufP = nil;
  284.  
  285. if(this->AnyMessagesForMe(anIACPtr))
  286.     {
  287.     aMsgPtr = this->GetMessage(anIACPtr->actualCount);
  288.     (void) aMsgPtr->IsMessageForMe(anIACPtr->mySignature,&sender,bufP);    
  289.     anIACPtr->partnerSig = sender;
  290.     tseStrCpy(anIACPtr->messageString,bufP);
  291.     tseStrCpy(anIACPtr->appName, this->GetAppName(anIACPtr->partnerSig));
  292.     this->SetMessage(anIACPtr->actualCount,nil);
  293.  
  294.         delete aMsgPtr;
  295.         return (kYesMessagesForMe);
  296.         }
  297. else
  298.         return(kNoMore);
  299. } // TDriver::ReceiveMessage
  300.  
  301. /************************Comment***************************
  302. * TDriver::UnregisterApp receives all the messages for the 
  303. * application that is unregistering. Those messages will 
  304. * just get thrown away. So, all the messages destined for 
  305. * it are disposed of, and then it sets the name to '\0' so
  306. * others can play.
  307.  ***********************End Comment***********************/
  308. short
  309. TDriver::UnregisterApp(IACRecord *anIACPtr)
  310. {
  311. char        zeroChar = kZeroChar;
  312.  
  313. // Gotta delete those suckers.
  314. while (this->ReceiveMessage(anIACPtr) == kYesMessagesForMe)            ;
  315. // Zero the name so others can play.
  316. this->SetAppName(anIACPtr->mySignature,&zeroChar);
  317. return (kNoErr);
  318. } // TDriver::UnregisterApp
  319.  
  320. Assembly Wrapped Around extern "C", Wrapped Around C++
  321. When you open the C++ Driver folder (Developer Essentials disc), you see many source files, including the files DriverGlue.a and DriverWrapper.cp. 
  322. The assembly glue performs three main functions: 
  323.  
  324. •    Pushing the appropriate registers onto the stack.
  325. •    Returning to the Device Manager in the proper manner.
  326. •    Setting up the DRVR resource with the appropriate routine offsets in the offset fields. 
  327.  
  328. The first two functions were covered earlier, but the third deserves some 
  329. further note.
  330.  
  331. If you just glance at the MPW(r) manual, creating the DRVR resource seems like a breeze. There's an entire section on it, right? Wrong. The section on building DRVRs is a good excursion into how to compile and link a DA (how they got to be DRVRs we'll never know), but only serves to mislead when it comes to "real" DRVR resources. 
  332.  
  333. MPW provides a great run-time library for DAs called DRVRRuntime.o, and it also provides a resource template that rez can use to create the final DRVR resource. The DRVW resource template included in MPWTypes.r even provides a nice programming description of the DRVR resource, but falls short when you delve into specifying the routine offsets every "device driver" needs to its Open/Prime/Control/Status/Close routines. The DRVRRuntime.o library simply provides jump statements to the appropriate pc-relative address for the DRVROpen, DRVRPrime, DRVRControl, DRVRStatus, and DRVRClose routines. Hence, the offsets are only 4 bytes apart, and right there the DRVR is hosed because the Device Manager has no way to jump to, say, the device driver's control routine. 
  334.  
  335. For example, say an Open routine is 48 bytes long. If you use the DRVW template, the DCE header will contain 0 as the offset for the Open routine, 4 as the offset for the Prime routine, 8 as the offset for the Control routine, and so on. When the Device Manager goes to call the Control routine, it will jump 8 bytes into the Open routine and start executing there - not what you had intended. The only recourse is to use DriverGlue.a as an entry point and define the offsets at the beginning of the assembly file (calculating the offsets appropriately). So much for having rez help out; maybe the assembler will be more helpful.
  336.  
  337. The "main" procedure, created to compensate for rez's ineffectiveness, 
  338. looks like this:
  339.  
  340. from DriverGlue.a
  341. HEADERDEF    PROC        EXPORT                                            
  342.         IMPORT     TSEPrime            
  343.         IMPORT     TSEOpen
  344.         IMPORT     TSEControl            
  345.         IMPORT     TSEStatus            
  346.         IMPORT     TSEClose    
  347. TSEStartHdr    DC.W        $5F00        ; Turn the proper bits on
  348.                         ; dNeedLock<6>, dNeedGoodbye<4)
  349.                         ; dReadEnable<3>, dWritEnable<2>
  350.                         ; dCtlEnable<1>, dStatEnable<0>
  351.         DC.W        $12C        ; 5 seconds of delay (if dNeedTime = True)
  352.         DC.W        0        ; DRVREMask (for DAs only)
  353.         DC.W        0        ; DRVRMenu (for DAs only)
  354.         DC.W        TSEOpen-TSEStartHdr    ; Offset to open routine.
  355.         DC.W        TSEPrime-TSEStartHdr    ; Offset to prime routine.
  356.         DC.W        TSEControl-TSEStartHdr    ; Offset to control routine.
  357.         DC.W        TSEStatus-TSEStartHdr    ; Offset to Status routine.
  358.         DC.W        TSEClose-TSEStartHdr    ; Offset to Close routine.
  359.  
  360. DC.B        '.TimDriver'; Driver name.
  361. ALIGN        4        ; Align to next long word.
  362. ENDP
  363.  
  364. It would be ideal to jump straight from the assembly language glue to the C++ TDriver methods and let the object do the work. Unfortunately, it's not that easy. First, we would have to allocate the TDriver object's space and put it into the dCtlHandle slot in the DCE. Second, we would have to do additional work in the glue code because each method implicitly expects that a pointer to the "this" object (the this pointer) will be passed on the stack. We would also have to stuff the dCtlStorage field into the "this" pointer address register.
  365.  
  366. The assembler isn't smart enough to figure out a directive like JMP TDRIVER::IACOpen. We could use the mangled name of the method and import that name at the start of the glue code, but all that seems a little too much for our assembly-naive minds. Apparently, then, the assembler isn't of much help either.
  367.  
  368. Instead, we'll resort to calling regular global C++ functions. We'll declare the functions as extern "C" functions so the compiler won't mangle the names, but will still compile them as regular C++ functions (because C++ is backward compatible with regular C). We end up with the following:
  369.  
  370. from DriverGlue.a
  371. ***************************** TSEOpen ***************************************
  372. * This routine (and all like it below) performs three basic functions:     
  373. * 1. Pushing the parameter block (A0) and the pointer to the DCE (A1)
  374. * on the stack.
  375. * 2. Testing to see whether the immediate bit was set in the trap word and,
  376. * if so, RTSing.
  377. * 3. Testing the result in D0. If it's 1, the operation hasn't completed
  378. * yet so we just want to RTS. If it's NOT 1, then we'll jump through 
  379. * jIODone.
  380. * I put the standard procedure header in just so you'd see another example of 
  381. * it in use. I found Sample.a to be most helpful in much of what I did here.
  382. *****************************************************************************
  383. TSEOpen    PROC    EXPORT            ; Any source file can use this routine.
  384.  
  385. StackFrame    RECORD    {A6Link},DECR    ; Build a stack frame record.
  386. Result1    DS.W        1            ; Function's result returned to caller.
  387. ParamBegin    EQU        *            ; Start parameters after this point.
  388. ParamSize    EQU        ParamBegin-*    ; Size of all the passed parameters.
  389. RetAddr     DS.L        1            ; Placeholder for return address.
  390. A6Link    DS.L        1            ; Placeholder for A6 link.
  391.  
  392. LocalSize    EQU         *            ; Size of all the local variables.
  393.         ENDR                    ; End of record definition.
  394.  
  395.         WITH        StackFrame        ; Cover our local stack frame.
  396.         LINK        A6,#LocalSize     ; Allocate our local stack frame.
  397.                 
  398.         MOVEM.L     D1-D3/A0-A4,-(A7)    ; Save registers (V1.1A).
  399.         MOVE.L    A1,-(A7)        ; Put address of DCE onto stack.
  400.         MOVE.L    A0,-(A7)        ; Put address of ParamBlock onto stack.
  401.         JSR         TSDRVROpen        ; Call our routine.
  402.         ADDQ.W    #$8,A7        ; Take off A0 and A1 we pushed.                ADDA.L        #ParamSize,SP    ; Strip all the caller's parameters.
  403.         MOVEM.L     (A7)+,D1-D3/A0-A4 ; Restore registers (V1.1A).
  404.         SWAP        D0            ; Save result in MostSig Word.
  405.         MOVE.W    ioTrap(A0),D0    ; Move ioTrap into register to test.
  406.         SWAP        D0            ; Back again.
  407.         BTST        #(noQueueBit+16), D0    ;Test the bit.
  408.         BNE.S        OpenRTS        ; If Z = 0, then noQueueBit. 
  409.                             ; Set  -  branch.
  410.         CMP.W        #$1,D0        ; Compare result with 1.
  411.         BEQ.S        OpenRTS        ; Not equal to zero so RTS.
  412.         UNLK        A6            ; Destroy the link.
  413.         MOVE.L    jIODone,-(A7)    ; Put jIODone on the stack.
  414.         RTS                    ; Return to the caller.
  415.  
  416. OpenRTS    UNLK        A6            ; Destroy the link.
  417.         RTS                    ; Return to the caller.
  418.         DbgInfo    TSEOpen        ; This name will appear in the debugger.
  419.         ENDP                    ; End of procedure.
  420.  
  421. These global functions will do only some minor work that amounts to getting a pointer to the driver and calling the appropriate method. The Open routine does have to instantiate the object and install it into the dCtlHandle field of the DCE for subsequent retrieval. And the Close routine has to reverse these effects and dispose of the memory allocated by the Open procedure. All in all, however, the code is straightforward and, again, easy to follow. 
  422.  
  423. from DriverWrapper.cp
  424. /********************************Comment*************************************
  425. * TSDRVROpen is called by the assembly TSEOpen routine. It in turn will simply 
  426. * turn around and call the TDriver::IACOpen method after some setup. This 
  427. * routine must instantiate the TDriver object. We'll be good heap users and move * the object (handle) hi. If we get an error, we'll return MemErr, mostly for 
  428. * debugging purposes. Declared as extern "C" in DriverWrapper.h
  429.  *******************************End Comment********************************/
  430.  
  431. OSErr     
  432. TSDRVROpen(ParmBlkPtr oParmBlock,DCtlPtr tsDCEPtr)
  433. {
  434. TDrvrPtr    aDrvrPtr;
  435. OSErr        err;
  436. // Create TDriver object.
  437. aDrvrPtr = new(TDriver);
  438.         
  439. // Make dCtlStorage point to it.
  440. tsDCEPtr->dCtlStorage = (Handle) aDrvrPtr;    
  441. if(tsDCEPtr->dCtlStorage)
  442.     {
  443.     MoveHHi(tsDCEPtr->dCtlStorage);
  444.     HLock(tsDCEPtr->dCtlStorage);
  445.     aDrvrPtr = (TDrvrPtr) tsDCEPtr->dCtlStorage;
  446.     err = aDrvrPtr->iacOpen(oParmBlock);    // Call the iacOpen() method.
  447.     HUnlock(tsDCEPtr->dCtlStorage);        
  448.     return(err);                        
  449.     }
  450. else
  451.     return MemError();
  452. }
  453.  
  454. /*********************************Comment**********************************
  455. * TSDRVRControl is called by the assembly TSEControl routine. It in turn 
  456. * simply turns around and calls the TDriver::IACControl method after locking 
  457. * the object. This essentially just locks the handle whose master pointer 
  458. * points to the object and then calls the appropriate method. When done, 
  459. * TSDRVRControl unlocks the handle.
  460. ********************************End Comment********************************/
  461. OSErr        
  462. TSDRVRControl(ParmBlkPtr cntlParmBlock,DCtlPtr tsDCEPtr)
  463. {
  464. TDrvrPtr    aDrvrPtr;
  465. OSErr        err;
  466.  
  467. HLock(tsDCEPtr->dCtlStorage);                // Lock the storage handle.
  468. aDrvrPtr = (TDrvrPtr) tsDCEPtr->dCtlStorage;    // Object pointer = master                                         // pointer.
  469. err = aDrvrPtr->iacControl(cntlParmBlock);    // Call the iacControl() method.
  470. HUnlock(tsDCEPtr->dCtlStorage);            // Unlock the handle.
  471. return(err);
  472. }
  473.  
  474. ***Figure 1: Using the Linker to Create the DRVR Resource ***
  475.  
  476. We now have three "kinds" of source files: (1) the assembly language glue, (2) the global C++ functions declared as extern "C" so the names will be normal (our driver "wrapper" functions), and (3) the C++ object methods. Having an assembly routine call a global C++ function, which calls a C++ method, seems like quite a hassle, but avoiding having to do the whole thing in assembly language is well worth the effort, especially with our friend Mr. Linker to put everything together.
  477.  
  478. Creating the DRVR Resource Itself
  479. The linker handles the entire task of creating the DRVR resource in the driver resource file. Here, again, there are some caveats about usage. First, you need to make sure that the first elements in a DRVR are the flags and offsets, so the first procedure in the assembly language file just defines these with DC.W instructions. Second, you have to tell the linker where the first procedure is, so you specify the 
  480. name with the -m option (in this case -m HeaderDef). Third, you have to give the DRVR resource the name you want the resource to have, so you use the -sn option to define this. Finally, you want to specify the resource attributes at link time, so you specify the DRVR resource as being locked, in the system heap, and preloaded. The link line looks like this:
  481.  
  482. from iacDriver.make
  483. Link -rt DRVR=75 -m HEADERDEF -sn "Main=.TimDriver" ∂
  484.         -c 'TSEN ' -t 'DRVR' ∂
  485.         -ra ".TimDriver"=resSysHeap,resLocked,resPreLoad ∂
  486.         {CPOBJECTS} ∂
  487.         "{Libraries}Interface.o" ∂
  488.         -o iacDriver.DRVR
  489.  
  490. Sometimes the compiler (or CFront) does things behind your back that are completely frustrating, even if you're a careful programmer. The first time I tried to link the driver together, the linker complained that data initialization code had not been called. I knew there was no "data initialization" code being called because I had compiled a stand-alone code resource. I scratched my head because I knew I didn't have any globals anywhere in my code. Then I remembered, "Oh yeah, the compiler puts string constants in the global segment." The MPW manual explains the -b option, and eventually that option worked to solve the problem. I say "eventually" because I ran into another case where the compiler helped me out without my knowing.
  491.  
  492. Definitions for new and delete are included in the CPlusLib.o library. In this case, CFront calls these functions for every constructor. Even if you define your own new and delete functions, the linker still will include the CPlusLib.o versions of the functions in the global segment. The linker then still thinks it has global data that hasn't been initialized. 
  493.  
  494. The solution to the problem is to define your own external "C" functions (an indicator to the compiler to use regular C calling conventions, but still part of your C++ code) with the mangled names for new and delete. You'll have to declare the functions as returning a void pointer or handle. The declarations look like this:
  495.  
  496. from iacGlobalNewDel.cp
  497. /* unmangle __nw__FUi
  498.  * Unmangled symbol: operator new(unsigned int)
  499.  * We return a void * because new returns a pointer.  */ void *__nw__FUi(unsigned int size)        
  500.  
  501.  
  502. ------
  503. As an alternative to defining  your own external "C" functions, you could use the A5 global library routines described in Technical Note #256, Stand-Alone Code, ad nauseam. You could then use globals as well as the default code for new and delete.•
  504.  
  505. /* unmangle __dl__FPv
  506.  * Unmangled symbol: operator delete(void *)
  507.  * We return void just for clarity.                        */
  508. void __dl__FPv(void *obj)                    
  509.  
  510. /* unmangle __nw__12HandleObjectSFUi
  511.  * Unmangled symbol: static HandleObject::operator new(unsigned int)
  512.  * We return a void ** because this version of new should return 
  513.  * a handle.                                    */
  514. void **__nw__12HandleObjectSFUi(unsigned int size)
  515.  
  516. /* unmangle __dl__12HandleObjectSFPPv
  517.  * Unmangled symbol: static HandleObject::operator delete(void **) */
  518. void __dl__12HandleObjectSFPPv(void **aHandle)
  519.  
  520. You have to use the mangled names because that's how they were compiled into the CPlusLib.o library. Fortunately, you can now eliminate the CPlusLib.o library from your list of libraries. Once past these two global obstacles - string constants placed in the global segment and new/delete operators called from constructors - the linker passes the sample code through with flying colors.
  521.  
  522. Building the 'Init' to Install the Driver
  523. Now that the DRVR resource and code are finished, how do you use it? The first order of business is to install the driver into the UnitTable. The listing for the code that does the installation appears on the next page. This code opens the resource file where the DRVR resides, looks for an open "slot" in the UnitTable starting from the rear of the UnitTable, opens the resource, changes the resource ID to match the UnitTable slot, calls OpenDriver, detaches the resource, and changes the DRVR resource ID back to what it was before beginning. The few steps that need explanation are finding the slot in the UnitTable, calling DetachResource, and calling OpenDriver.
  524.  
  525. Why do you have to find an open slot in the UnitTable? You want to make sure the driver gets installed. If there's a resource ID conflict (and hence a slot conflict in the UnitTable), you can't be sure whether the driver will clobber the existing one or won't get installed at all. Thus, you could rely on just calling OpenDriver with the DRVR resource ID, but that wouldn't be very cooperative of you. So you look for an open slot, which boils down to looking for a nil address in the UnitTable, starting at the back of the UnitTable where open slots are most likely to exist (the system uses up slots at the beginning of the UnitTable). If the contents of the address are nil, you can install the driver into that slot.
  526.  
  527. from installDriver.c 
  528. short 
  529. lookForSlotInUnitTable()
  530. {
  531. short        slot;
  532. Ptr        theBass;
  533. long        *theVoidPtr;
  534. Boolean     foundSlot = false;
  535.  
  536. /* Set up variables based on contents of low-memory global
  537.  * locations.  DTS tells people not to rely on low-memory 
  538.  * globals, but we really need these two low-memory 
  539.  * globals to do our work. So, there is a compatibility
  540.  * risk we have to be aware of.                     */
  541.  
  542. slot = *((short *)(UnitNtryCnt)) - 1;
  543. theBass = (Ptr) (*((long *) (UTableBase)));
  544.  
  545. // We step back to 48 because 0-47 are taken.
  546. while(slot>48 && !foundSlot)     
  547.         {
  548.         theVoidPtr = (long *)(theBass + (4L * slot));
  549.         
  550.         if(*theVoidPtr == nil)
  551.             foundSlot = true;
  552.             
  553.         slot -= 1;
  554.         }
  555.     
  556. slot += 1;
  557. if(!foundSlot)
  558.     slot = 0;    
  559. return slot;
  560. }
  561.  
  562. Why do you call DetachResource? Inside Macintosh, volume V, page 121, says, "DetachResource is also useful in the unusual case that you don't want a resource to be released when a resource file is closed." The example is such a case. When the Init is loaded and executed by the Init 31 mechanism, the resource file in which the Init resides is opened. When the Init has been executed, the resource file is closed, and the Resource Manager goes around and cleans up any of the resources in the resource map that are known to be allocated. DetachResource replaces the handle in the resource map with nil, so the Resource Manager thinks it doesn't have to clean up that handle.
  563.  
  564. ----
  565. Thanks to Pete Helme for the installDriver.c code. •
  566.  
  567. Why do you call OpenDriver instead of _DrvrInstall? Essentially that's because OpenDriver does the correct thing and _DrvrInstall doesn't. When you call _DrvrInstall with a handle to the driver, _DrvrInstall does most of the work, but it forgets to put the handle to the driver into the dCtlDriver field of the DCE and effectively makes the driver unreachable. _OpenDriver has no such problem, and it works correctly. Alternatively, you could use _DrvrInstall and then put the handle to the driver into the DCE. 
  568. The installation code looks like this:
  569.  
  570. from installDriver.c
  571. void
  572. changeDRVRSlot(short slot)     
  573. {
  574. Handle        theDRVR;
  575. short            err, refNum;
  576. char            *name, DRVRname[256];
  577. short            DRVRid;
  578. ResType        DRVRType;
  579.  
  580. name = "\p.TimDriver";
  581.  
  582. if(slot != 0) {        
  583.     theDRVR = GetNamedResource('DRVR', name);
  584.     GetResInfo(theDRVR, &DRVRid, &DRVRType, &DRVRname);
  585.     SetResInfo(theDRVR, slot, 0L);
  586.      
  587.     err = OpenDriver(name, &refNum);
  588.     if(err == noErr)
  589.         {
  590.         /* Detach the resources from the resource map. */
  591.         DetachResource(theDRVR);
  592.  
  593.         }
  594.     /* Restores the previous resource attributes so they don't change
  595.      * from start-up to start-up. We just want the in-memory copy to
  596.      * have a different ID - not our resource in the file. */
  597.     theDRVR = GetNamedResource('DRVR', name);
  598.     SetResInfo(theDRVR, DRVRid, nil);
  599.     }
  600. }
  601.  
  602. This code needs to be compiled with the -b option as well because it's a stand-alone code resource like the DRVR, and you have to have everything in one resource. For the example, we chose to make the installation code an Init so that the driver will install at system start-up time and so that any application can access it. You also must make sure that the resource has the resource attribute resLocked. The Init must be locked at start-up time in case anything in the Init code moves memory. If anything in the Init does move memory, you come back to some random place in the system heap because the Init resource has been moved. This is a particularly painful (and time-consuming) gotcha.
  603.  
  604. Putting It All Together
  605. The final goal is to have one file that contains all the necessary resources. At this point you have all the code resources you need: the Init and the DRVR. You may need one additional resource, depending on how large the driver is and how much of the system heap you need. If you need more than 16K, you have to create the sysz resource and put that in the file. Fortunately, the sysz resource is simple to define; it looks like this:
  606.  
  607. from iacDriver.r
  608. include "iacDriver.DRVR"; /* Include the DRVR resource.    */
  609. include "installDriver";     /* Include the INIT resource.    */
  610.  
  611. type 'sysz' {  /* This is the type definition. */
  612.     longint;     /* Size requested (see IM V, page 352).*/
  613. };
  614.  
  615. resource 'sysz' (0,"",0) { /* This is the declaration.    */
  616.     0x00008000    /* 32 * 1024 bytes for sysz resource.    */
  617. };
  618.  
  619. Now that you have all the components, you let rez do the work of moving the Init and DRVR resources into one file. Fortunately you can include resources from other resource files with the "include" directive (see chapter 11, page 309, in the MPW manual for a discussion of rez).
  620.  
  621. from iacDriver.make
  622. rez iacDriver.r -c TSEN -t INIT -a -o iacDriver
  623.  
  624. Calling the Driver From an Application
  625. The example also includes several routines you might run from a client application to use the sample driver. Developer Essentials contains two sample applications that use these routines to register and send or receive messages. (Don't get your hopes up, though. This is just Sample.c modified, so the light will turn off and on via control from a second application.)
  626.  
  627. DESIGN DECISIONS
  628. Now that you've learned about this "device driver" in particular, and more about drivers in general, we can discuss some of the trade-offs required. 
  629.  
  630. What to Do With jIODone, and When
  631. Most of the time, the device driver should jump to jIODone so the Device Manager will handle the housekeeping tasks of marking the driver as "unbusy" and calling the completion routine. However, a few exceptions are noted throughout the chapter on the Device Manager (Inside Macintosh, volume II, chapter 6). You don't want to jump to jIODone (just RTSing instead) in these situations:
  632.  
  633. •    When an operation you started is not yet complete (that is, an operation that will interrupt you when it is complete).
  634. •    When you get a KillIO request.
  635. •    When you get called immediately (that is, bit #9, the noQueueBit, is set in the ioTrap word and calls usually look like _Read, IMMED).
  636.  
  637. Speaking of the immediate bit, you'll find that most drivers don't guard against reentrancy. This is a problem when callers try to make Immediate calls to the driver. If you don't want people making Immediate calls to the driver, you have to specify in the documentation that callers may not call this device driver immediately; otherwise, the results will be indeterminate. On the other hand, if you do want to allow Immediate calls, one simple way to guard against most types of reentrancy problems is to set some flag within the driver and then either (1) return without performing the immediate action requested or (2) save the state of the other operation, perform the Immediate call, and return. In either event, remember to return via an RTS for all Immediate calls.
  638.  
  639. Multiple Outstanding Requests
  640. You may want a driver to be able to handle many _Read and _Write requests at the same time, and not one at a time. This driver can handle only one request at a time. If no messages are waiting when requested, for example, the caller is told there are no messages. In many cases, however, you want to keep that request around until there is a message. To handle this case, you have to do some more work. Essentially, you have to dequeue the request from the Device Manager's queue, queue it up in some internal list of your own, and then satisfy the requests when they are finished. You have to perform the functionality of jIODone yourself as well, because you'll be handling the operations yourself. You're also operating behind the Device Manager's back to some extent because you're dequeueing requests from the I/O queue yourself.
  641.  
  642. _Read and _Write or _Control Operations
  643. If you use _Read and _Write, you can't pass in csParam. The trade-off we made in the example was that csParam would point to a structure that gave us more control over, and a more elegant solution to, sending and receiving messages to and from the proper place. If you use _Read/_Write, you have to format the ioBuffer to contain all the information for the messages, and that means encoding the sender and receiver signatures in with the actual message. One disadvantage of this trade-off is that the method may fail in the future in the world of virtual memory. Virtual memory watches the _Read and _Write traps and makes sure the memory addressed by ioBuffer stays in physical memory, but it neglects to do the same for csParam. Hence, the IACRecord structure (and pointers within that structure) may or may not be in physical RAM at the time of the call. If this happens at interrupt time and a page fault occurs, you're completely hosed.
  644.  
  645. TMessage Objects
  646. Finally, the sample driver isn't very space friendly. The TMessage objects are allocated by NewPtrSys, and hence will fill up the system heap with locked pointers. The good news is that TMessage objects probably don't live for very long. The bad news is that the heap may still become fragmented. So, another design decision you could make would be to derive from HandleObject and take into consideration dereferences of handles. You may want to try that as an exercise.
  647.  
  648. ----
  649. For More Information
  650. Inside Macintosh, volume II, chapter 6, "The Device Manager."
  651. Stanley Lippman: The C++ Primer, Addison-Wesley, 1989.
  652. Bjarne Stroustrup: The C++ Programming Language, Addison-Wesley, 1987. •
  653.  
  654. SUMMING UP
  655. To summarize: C++ can be used to write a device driver that operates under some basic restrictions. We successfully built a couple of stand-alone classes that can be modified and kept up separately. The classes present a clear definition of roles and hide data as cleanly as possible. We chose not to use polymorphism in the code, although we certainly could have done so - with a little extra work and the possibility of future incompatibilities (again, see "Polymorphic Code Resources in C++," by Patrick Beard, in this issue). 
  656.  
  657. Because of limitations of the operating system and development system, we have to incorporate some assembly language, and some global C++ functions, into whatever we write. We discussed some of the design trade-offs you must inevitably make and went into some depth on several of the trickier aspects of writing a device driver - what to do with jIODone, how to use the assembler to best advantage, compiling and linking the stand-alone code so it does the right thing, creating an Init that installs the driver at system start-up time, and using rez to create the eventual resource file.
  658.  
  659. C++ allows you to encapsulate data with functions, thus making it easier to maintain code and port the code to other platforms. Some nifty language features, such as function overloading and strong type checking, come with C++. If you're writing a device driver that doesn't depend on speed and efficiency, C++ is a good choice of languages.
  660.  
  661.  
  662. * * * photo * * *
  663.  
  664. TIM  ENWALL,  DTS engineer, is a four-year Apple veteran. He's done stints in Technical Resources and data base applications, and has answered the A/UX(r) hotline. Now his primary job purportedly revolves around IBM connectivity (although no one ever seems to ask him about it). 
  665.  
  666. The rest of his time is spent with networking and lower-level device managers. A Rocky Mountain native, he came to Cal Berkeley for an EE/CS degree. He likes bike riding, cooking, playing softball, and long talks with friends. Two Burmese cats - Bella and GBU (for the Good, the Bad, and the Ugly, pronounced "Boo") - guard him during his off hours. Two favorite books have helped shape his outlook: Light in August by William Faulkner and Native Son by Richard Wright. But don't let his serious side fool you. Watch out when he's sitting across a poker table from you: he was brought up on cards, and he's out to get that BMW 3.0CSi with a sunroof. Will you be the one to provide the down payment? • 
  667.  
  668. ----
  669. Thanks to Our Technical Reviewers
  670. Brian Bechtel and Jack Palevich •
  671.  
  672.  
  673.  
  674.  
  675.  
  676.  
  677.  
  678.  
  679.  
  680.  
  681.  
  682.  
  683.  
  684.  
  685.  
  686.